package com.ssnst.wechat.controller;

import com.ssnst.wechat.service.MessageService;
import com.ssnst.wechat.util.WeChatUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.logging.Logger;

/**
 * @ClassName：wechatController
 * @Description：微信Controller
 * @Author：Hirsi
 * @Time：2019/7/25 12:30
 * @Version：1.0
 */
@RestController
public class MessagetController {

    @Resource
    private MessageService messageService;

    private static Logger log = Logger.getLogger(MessagetController.class.getName());

    /**
     *@MethodName：validate
     *@Description：处理微信服务器发来的get请求，进行签名的验证
     *@Author：Hirsi
     *@Time：2019/7/25 13:06
     *@Param：[request, response]
     *@Return：java.lang.String
     */
    @GetMapping("wechat")
    public String validate(HttpServletRequest request, HttpServletResponse response){
        log.info("Get请求来咯");
        Enumeration enu=request.getParameterNames();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            System.out.println(paraName+": "+request.getParameter(paraName));
        }
        if (StringUtils.isNotBlank(request.getParameter("signature"))) {
            //微信加密签名
            String signature = request.getParameter("signature");
            //时间戳
            String timestamp = request.getParameter("timestamp");
            //随机数
            String nonce = request.getParameter("nonce");
            //随机字符串
            String echostr = request.getParameter("echostr");
            System.out.println(echostr);
            if (WeChatUtil.checkSignature(signature, timestamp, nonce)) {
                return echostr;
            } else {
                return null;
            }
        } else {
            return null;
        }
    }
    @PostMapping(value = "wechat")
    public String processMsg(HttpServletRequest request) {
        // 调用核心服务类接收处理请求
        log.info("post请求来咯");
        return messageService.processRequest(request);
    }

    @RequestMapping("test")
    public String returnStr(HttpServletRequest request, HttpServletResponse response){
        //测试用
//        System.console().printf("111111");
        log.info("Log实例可以使用了");
        return "HelloWord!";
    }
}
